<?php
namespace StarCloud\Services\Export;

use StarCloud\Library\Exception;
use StarCloud\Models\Huoshi\BossTaskExport;
use StarCloud\Services\BaseService;
use StarCloud\Services\QueueService;

class TaskExportService extends BaseService
{
    const BOSS_TASK_FLAG_1 = 101;

    const TASK_MAP = [
        BossTaskExport::class => [
            self::BOSS_TASK_FLAG_1 => '导出Boss Demo',
        ],
    ];

    public static $instance;
    private $model;
    private $type;

    const TYPE_BOSS = 'boss';

    private function __construct($type)
    {
        $this->type = $type;
        switch ($type) {
            case self::TYPE_BOSS:
                $this->model = BossTaskExport::class;
                break;
        }
    }

    public static function getInstance($type)
    {
        if (empty(self::$instance)) {
            self::$instance = new self($type);
        }

        return self::$instance;
    }

    public function getList($arrInput)
    {
        $page = $arrInput['page'] ?? 1;
        $count = $arrInput['count'] ?? 10;

        return call_user_func_array([$this->model, 'getPaginatorArrayResultByUid'], [$arrInput['uid'], $page, $count]);
    }

    public function newExportTask($taskFlag, array $taskParams, $uid)
    {
        if (!isset(self::TASK_MAP[$this->model][$taskFlag])) {
            throw new Exception(10002);
        }
        $taskName =self::TASK_MAP[$this->model][$taskFlag];

        $task = call_user_func_array([$this->model, 'newTask'], [$taskFlag, $taskName, $taskParams, $uid]);

        // TODO 消息队列导出任务
        QueueService::putToTuBe(QueueService::TUBE_BACKEND_CSV_FILE_EXPORT, ['class' => $this->model, 'task_id' => $task->getId()]);

        return $task;
    }
}
